package com.github.wui.ktEx

import android.os.Handler
import android.os.Looper
import android.os.Message


/**
 * 线程扩展
 * @author <a href="https://github.com/karai-oss">Mr.xie</a>
 * @Date 2025/4/19
 */


private enum class ThreadWhat {
    NO_PARAMS,
    HAVE_PARAMS_THREAD // 带参数和线程
}

/**
 * 内部 handler 用于转UI线程
 */
private class UIHandler(looper: Looper) : Handler(looper) {
    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        val what = msg.what as Int
        when (what) {
            ThreadWhat.NO_PARAMS.ordinal -> {
                val runnable = msg.obj as Runnable
                runnable.run()
            }

            ThreadWhat.HAVE_PARAMS_THREAD.ordinal -> {
                val objects = msg.obj as MutableList<*>
                val runnable = objects.get(objects.size - 1) as ThreadCallBack
                runnable(objects)
            }
        }

    }
}


/**
 * 没有参数转UI线程
 */
fun Any.toMainThread(run: Runnable) {
    val mainHandler = UIHandler(Looper.getMainLooper())
    val message = Message.obtain()
    message.obj = run;
    message.what = ThreadWhat.NO_PARAMS.ordinal;
    mainHandler.sendMessage(message);
}


/**
 * 带参数的UI线程切换
 */
fun Any.toParamsMainThread(vararg args: Any, args2: ThreadCallBack) {
    val mainHandler = UIHandler(Looper.getMainLooper())
    val message = Message.obtain()
    val argsList = args.toMutableList()
    argsList.add(args2)
    message.obj = argsList
    message.what = ThreadWhat.HAVE_PARAMS_THREAD.ordinal
    mainHandler.sendMessage(message);
}


/**
 * UI线程中 退出APP
 */
fun Any.exitApp(){
    val myLooper = Looper.myLooper()
    if (myLooper != null && myLooper == Looper.getMainLooper()){
        myLooper.quitSafely()
    }
}

typealias ThreadCallBack = (args: Any) -> Unit
